package com.demo.service;

import com.demo.bean.User;
import com.demo.common.Result;
import com.demo.dao.RecordDao;
import com.demo.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class RecordService {
    @Autowired
    private RecordDao dao;
    @Autowired
    private UserDao userDao;

    /**
     * 根据用户名获取打卡记录列表
     * @param loginname
     * @return
     */
    public Result getByLoginname(String loginname){
       List<Map> recordList = dao.getByLoginname(loginname);
       return Result.ok().Data(recordList);
    }

    /**
     * 根据用户名获取当天打卡记录列表
     * @param loginname
     * @return
     */
    public Result getCurrentByLoginname(String loginname){
        Map record = dao.getCurrentByLoginname(loginname);
        return Result.ok().Data(record);
    }

    public Result addRecord(String loginname) {
        Map record=new HashMap();
        User user = userDao.getByloginname(loginname);
        Map latestRecord=dao.getLatestRecordById(user.getId());
        Date now=new Date();
        if(latestRecord!=null){
            Date startTime = (Date) latestRecord.get("startTime");
            Date endTime = (Date) latestRecord.get("endTime");
            //5400秒是一个半小时,如果再次打卡时间设置为一个半小时之后
            if(now.getTime()-startTime.getTime()>5400000&&endTime==null){
                endTime=new Date(startTime.getTime()+5400000);
                latestRecord.put("endTime",endTime);
                dao.updateItem(latestRecord);
            }
            //要是小于一个半小时打卡，就删除上个记录
            if(now.getTime()-startTime.getTime()<5400000&&endTime==null){
                dao.delRecordById(latestRecord.get("id").toString());
            }
        }


        record.put("userId",user.getId());
        record.put("startTime",new Date());
        dao.addItem(record);
        return Result.ok();
    }

    public Result endRecord(String loginname) {
        Map record=new HashMap();
        User user = userDao.getByloginname(loginname);
        record.put("userId",user.getId());
        record.put("endTime",new Date());
        dao.updateItem(record);
        return Result.ok();
    }

    public Result getTotalTime(String loginname) {
        Long totalSecond=dao.getTotalTime(loginname);
        if(totalSecond==null){
            totalSecond=0L;
        }
        System.out.println("totalTime"+totalSecond);
        String totalTime=getDate(totalSecond);
        return Result.ok().Data(totalTime);
    }

    /**
     * 转换秒为时分秒的形式
     *
     * @param seconds 待转换的秒
     * @return
     */
    public static String getDate(Long seconds) {
        long h = seconds / 3600;
        long m = (seconds % 3600) / 60;
        long s = (seconds % 3600) % 60;
        return h + "小时" + m + "分" + s + "秒";
    }

}
